import { createContext, useContext, useEffect, useState } from "react";

// 上下文
export const appContext = createContext(null);

export const store = {
    state: {
        user: {
            name: 'tom',
            age: 99
        }
    },
    setState (newState) {
        store.state = newState;
        store.listeners.map(fn => fn(store.state));
    },
    listeners: [],
    subscribe (fn) {
        store.listeners.push(fn);
        return () => {
            const index = store.listeners.indexOf(fn);
            store.listeners.splice(index, 1); // 取消订阅
        }
    },
}

// reduce 用于规范 state 创建流程的函数
const reducer = (state, {type, payload = {}}) => {
    if (type === 'updateUser') {
        return {
            ...state,
            user: {
                ...state.user,
                ...payload
            }
        }
    } else {
        return state;
    }
}

// 高阶组件
export const connect = (Component) => {
    const Wrapper = (props) => {
        const { state, setState } = useContext(appContext);
        const [, update] = useState({}); // 只会一个组件的更新,有 bug, 解决方案,使用发布订阅

        useEffect(() => {
            // 订阅, 解决只刷新一个组件的问题
            store.subscribe(() => {
                update({});
            });
        }, [])
        // dispatch 用于规范 setState 的流程
        const dispatch = (action) => {
            setState(reducer(state, action));
            // update({}); // 强制刷新 只会一个组件的更新,有 bug, 解决方案,使用发布订阅
        }
        return <Component {...props} dispatch={dispatch} state={state}/>
    }

    return Wrapper;
}
